package com.zb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.*;
import com.zb.mapper.ZjWithdrawRecordMapper;
import com.zb.mobile.NetworkWithdrawOrderDetailVo;
import com.zb.service.*;
import com.zb.view.ViewNetworkEmpAccount;
import com.zb.vo.FinishWithdrawVo;
import com.zb.vo.WithdrawDetail;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Service
public class ZjWithdrawRecordServiceImpl extends ServiceImpl<ZjWithdrawRecordMapper, ZjWithdrawRecord> implements ZjWithdrawRecordService {
    @Resource
    private ZjWithdrawOrderService zjWithdrawOrderService;
    @Resource
    private ZjWithdrawService withdrawService;
    @Resource
    private ZjWithdrawVoucherService withdrawVoucherService;
    @Resource
    private ZjWorkOrderService workOrderService;
    @Resource
    private ZjWithdrawOrderService withdrawOrderService;
    @Resource
    private ZjNetworkService networkService;
    @Resource
    private ZjWithdrawCheckEmpService withdrawCheckEmpService;
    @Resource
    private ViewNetworkEmpAccountService viewNetworkEmpAccountService;
    @Resource
    private ZjWorkUserService workUserService;
    @Resource
    private ZjWorkModuleService workModuleService;
    @Resource
    private ZjWithdrawSetService withdrawSetService;
    @Resource
    private ZjWithdrawRecordService zjWithdrawRecordService;
    /**
     * 保存到表ZjWithdrawRecord
     * */
    @Override
    public void saveWithdrawRecord(List<ZjWithdraw> withdraws, FinishWithdrawVo withdrawVo) {
        List<ZjWithdrawRecord> zjWithdrawRecords = new ArrayList<>();
        withdraws.forEach(withdraw -> {
            ZjWithdrawRecord zjWithdrawRecord = new ZjWithdrawRecord();
            List<ZjWithdrawOrder> byWithdrawId = zjWithdrawOrderService.getByWithdrawId(withdraw.getId());
            BigDecimal total = new BigDecimal(0);
            WithdrawDetail detail = this.getWithdraw(withdraw.getId());
            BigDecimal handingFeeFixedOrder = withdraw.getHandingFeeFixedOrder();
            List<NetworkWithdrawOrderDetailVo> withdrawOrder = this.getWithdrawOrder(withdraw.getId());
            for (NetworkWithdrawOrderDetailVo networkWithdrawOrderDetailVo : withdrawOrder) {
                total= total.add(networkWithdrawOrderDetailVo.getWithdrawMoney());
                total= total.subtract(handingFeeFixedOrder);
            }
            zjWithdrawRecord.setId(withdraw.getId())
                    .setApplyNetworkEmpId(withdraw.getApplyNetworkEmpId())
                    .setRequestSn("")
                    .setCreditNo("")
                    .setAmount(total)
                    .setAccount(withdraw.getBankNo())
                    .setAccountName(withdraw.getCardholderName())
                    .setBankName(withdraw.getName())
                    .setIsPush(false)
                    .setBankCode(withdraw.getBankCode())
                    .setOpenAccountBankNetwork(withdraw.getOpenAccountBankNetwork())
                    .setCallbackResult("");
            zjWithdrawRecords.add(zjWithdrawRecord);
        });
        this.saveOrUpdateBatch(zjWithdrawRecords);
    }

    private WithdrawDetail getWithdraw(Long id){
        ZjWithdraw withdraw = withdrawService.getById(id);
        Assert.notNull(withdraw, "查无此提现单：" + id);
        WithdrawDetail detail = new WithdrawDetail();
        BeanUtil.copyProperties(withdraw, detail);
        detail.setCreateTime(withdraw.getGmtCreate());
        detail.setPaths(withdrawVoucherService.getByWithdrawId(id));
        return detail;
    }

    // 根据提现单ID获取提现工单
    private List<NetworkWithdrawOrderDetailVo> getWithdrawOrder(Long withdrawId) {
        QueryWrapper<ZjWithdrawOrder> withdrawOrderQueryWrapper = new QueryWrapper<>();
        withdrawOrderQueryWrapper.select("id", "work_id", "work_no", "old_withdraw_money", "withdraw_money")
                .eq("withdraw_id", withdrawId);
        List<ZjWithdrawOrder> withdrawOrderList = withdrawOrderService.list(withdrawOrderQueryWrapper);
        List<Long> workIds = withdrawOrderList.stream().map(ZjWithdrawOrder::getWorkId).toList();
        Map<String, List<String>> engineerMap = new HashMap<>();
        List<ZjWorkUser> userList = new ArrayList<>();
        Map<String, String> workModuleMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(workIds)) {
            QueryWrapper<ZjWorkOrder> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.select("id", "network_emp_id")
                    .in("id", workIds);
            List<ZjWorkOrder> orderList = workOrderService.list(orderQueryWrapper);
            List<Long> networkEmpIds = orderList.stream().map(ZjWorkOrder::getNetworkEmpId).distinct().toList();
            if (CollectionUtil.isNotEmpty(networkEmpIds)) {
                List<ViewNetworkEmpAccount> accountList = viewNetworkEmpAccountService.getByIds(networkEmpIds);
                ViewNetworkEmpAccount empAccount = null;
                List<String> emps = null;
                for (ZjWorkOrder order : orderList) {
                    empAccount = accountList.stream().filter(f -> Objects.equals(f.getId(), order.getNetworkEmpId())).findFirst().orElse(null);
                    if (null != empAccount) {
                        emps = new ArrayList<>();
                        emps.add(empAccount.getName());
                        emps.add(empAccount.getPhone());
                        engineerMap.put(order.getId().toString(), emps);
                    }
                }
                QueryWrapper<ZjWorkUser> workUserQueryWrapper = new QueryWrapper<>();
                workUserQueryWrapper.select("id", "name", "phone")
                        .in("id", workIds);
                userList.addAll(workUserService.list(workUserQueryWrapper));
            }
            // 获取工单模块类型
            List<Long> moduleIds = orderList.stream().map(ZjWorkOrder::getModuleId).distinct().toList();
            List<ZjWorkModule> moduleList = workModuleService.getPartInfoByIds(moduleIds);
            ZjWorkModule module = null;
            for (ZjWorkOrder order : orderList) {
                module = moduleList.stream().filter(f -> Objects.equals(f.getId(), order.getModuleId())).findFirst().orElse(null);
                workModuleMap.put(order.getId().toString(), null == module? "" : module.getName());
            }
        }
        List<NetworkWithdrawOrderDetailVo> withdrawOrderDetailVos = withdrawOrderList.stream().map(withdrawOrder -> {
            NetworkWithdrawOrderDetailVo vo = new NetworkWithdrawOrderDetailVo();
            vo.setId(withdrawOrder.getId());
            vo.setWorkId(withdrawOrder.getWorkId());
            vo.setWorkNo(withdrawOrder.getWorkNo());
            vo.setModule(workModuleMap.get(withdrawOrder.getWorkId().toString()));
            vo.setWithdrawMoney(withdrawOrder.getWithdrawMoney());
            vo.setOldWithdrawMoney(withdrawOrder.getOldWithdrawMoney());
            List<String> emps = engineerMap.get(withdrawOrder.getWorkId().toString());
            if (CollectionUtil.isNotEmpty(emps)) {
                vo.setEngineer(emps.get(0));
                vo.setEngineerPhone(emps.get(1));
            }
            userList.stream().filter(f -> Objects.equals(f.getId(), withdrawOrder.getWorkId())).findFirst().ifPresent(user -> {
                vo.setUsername(user.getName());
                vo.setUserPhone(user.getPhone());
            });
            return vo;
        }).toList();
        return withdrawOrderDetailVos;
    }
}
